<template>
  <div class="teacher-detail" v-loading="loading">
    <!-- 教师基本信息 -->
    <div class="teacher-header">
      <div class="teacher-info">
        <div class="avatar-wrapper">
          <img :src="teacherInfo.avatar" :alt="teacherInfo.name" class="avatar">
          <div class="title-tag">{{ getTitleText(teacherInfo.title) }}</div>
        </div>
        <div class="info-content">
          <h1 class="name">{{ teacherInfo.name }}</h1>
          <div class="subject">{{ getSubjectText(teacherInfo.subject) }}</div>
          <div class="stats">
            <div class="stat-item">
              <i class="el-icon-reading"></i>
              <span>{{ teacherInfo.courseCount }}门课程</span>
            </div>
            <div class="stat-item">
              <i class="el-icon-user"></i>
              <span>{{ teacherInfo.studentCount }}名学生</span>
            </div>
            <div class="stat-item">
              <i class="el-icon-star-on"></i>
              <span>{{ teacherInfo.rating }}分</span>
            </div>
          </div>
          <div class="actions">
            <el-button 
              type="primary" 
              :class="{ 'is-following': isFollowing }"
              @click="handleFollow"
            >
              {{ isFollowing ? '已关注' : '关注' }}
            </el-button>
            <el-button type="primary" plain @click="showAskDialog">
              向老师提问
            </el-button>
          </div>
        </div>
      </div>
      <div class="teacher-intro">
        <h3>个人简介</h3>
        <p>{{ teacherInfo.introduction }}</p>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="content-section">
      <el-tabs v-model="activeTab">
        <!-- 课程列表 -->
        <el-tab-pane label="课程" name="courses">
          <div class="course-list">
            <el-row :gutter="20">
              <el-col :xs="24" :sm="12" :md="8" v-for="course in courses" :key="course.id">
                <router-link :to="`/course/${course.id}`" class="course-card">
                  <div class="course-cover">
                    <img :src="course.cover" :alt="course.title">
                  </div>
                  <div class="course-info">
                    <h3 class="title">{{ course.title }}</h3>
                    <div class="stats">
                      <span>
                        <i class="el-icon-user"></i>
                        {{ course.studentCount }}人学习
                      </span>
                      <span>
                        <i class="el-icon-document"></i>
                        {{ course.chapterCount }}章节
                      </span>
                    </div>
                  </div>
                </router-link>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>

        <!-- 学习资料 -->
        <el-tab-pane label="资料" name="materials">
          <div class="material-list">
            <div v-for="material in materials" :key="material.id" class="material-item">
              <router-link :to="`/material/${material.id}`" class="material-link">
                <div class="material-icon">
                  <i :class="getMaterialIcon(material.type)"></i>
                </div>
                <div class="material-info">
                  <h3 class="title">{{ material.title }}</h3>
                  <div class="meta">
                    <span>{{ material.type | materialType }}</span>
                    <span>{{ material.size | fileSize }}</span>
                    <span>{{ material.downloadCount }}次下载</span>
                  </div>
                </div>
              </router-link>
            </div>
          </div>
        </el-tab-pane>

        <!-- 评价 -->
        <el-tab-pane label="评价" name="reviews">
          <div class="review-section">
            <div class="review-stats">
              <div class="rating-overview">
                <div class="rating-score">
                  <span class="score">{{ teacherInfo.rating }}</span>
                  <el-rate v-model="teacherInfo.rating" disabled></el-rate>
                </div>
                <div class="rating-distribution">
                  <div v-for="(count, index) in ratingDistribution" :key="index" class="rating-bar">
                    <span class="star-label">{{ 5 - index }}星</span>
                    <el-progress 
                      :percentage="(count / totalReviews) * 100"
                      :show-text="false"
                    ></el-progress>
                    <span class="count">{{ count }}</span>
                  </div>
                </div>
              </div>
            </div>
            <div class="review-list">
              <div v-for="review in reviews" :key="review.id" class="review-item">
                <div class="reviewer-info">
                  <img :src="review.avatar" :alt="review.username" class="avatar">
                  <span class="username">{{ review.username }}</span>
                  <el-rate v-model="review.rating" disabled></el-rate>
                  <span class="time">{{ review.createTime }}</span>
                </div>
                <div class="review-content">{{ review.content }}</div>
              </div>
            </div>
            <div class="pagination">
              <el-pagination
                background
                layout="prev, pager, next"
                :total="totalReviews"
                :page-size="reviewPageSize"
                @current-change="handleReviewPageChange"
              ></el-pagination>
            </div>
          </div>
        </el-tab-pane>

        <!-- 问答 -->
        <el-tab-pane label="问答" name="questions">
          <div class="question-list">
            <div v-for="question in questions" :key="question.id" class="question-item">
              <div class="question-header">
                <img :src="question.avatar" :alt="question.username" class="avatar">
                <span class="username">{{ question.username }}</span>
                <span class="time">{{ question.createTime }}</span>
              </div>
              <div class="question-content">
                <h3 class="title">{{ question.title }}</h3>
                <p class="content">{{ question.content }}</p>
              </div>
              <div class="answer" v-if="question.answer">
                <div class="answer-header">
                  <img :src="teacherInfo.avatar" :alt="teacherInfo.name" class="avatar">
                  <span class="name">{{ teacherInfo.name }}</span>
                  <span class="time">{{ question.answerTime }}</span>
                </div>
                <div class="answer-content">{{ question.answer }}</div>
              </div>
            </div>
          </div>
          <div class="pagination">
            <el-pagination
              background
              layout="prev, pager, next"
              :total="totalQuestions"
              :page-size="questionPageSize"
              @current-change="handleQuestionPageChange"
            ></el-pagination>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 提问对话框 -->
    <el-dialog
      title="向老师提问"
      :visible.sync="askDialogVisible"
      width="50%"
    >
      <el-form :model="questionForm" :rules="questionRules" ref="questionForm">
        <el-form-item label="问题标题" prop="title">
          <el-input v-model="questionForm.title" placeholder="请输入问题标题"></el-input>
        </el-form-item>
        <el-form-item label="问题内容" prop="content">
          <el-input
            type="textarea"
            v-model="questionForm.content"
            :rows="4"
            placeholder="请详细描述你的问题"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="askDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitQuestion">提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import api from '@/api'

export default {
  name: 'TeacherDetail',
  data() {
    return {
      loading: false,
      teacherId: this.$route.params.id,
      teacherInfo: {},
      isFollowing: false,
      activeTab: 'courses',
      courses: [],
      materials: [],
      reviews: [],
      questions: [],
      ratingDistribution: [0, 0, 0, 0, 0],
      totalReviews: 0,
      totalQuestions: 0,
      reviewPageSize: 10,
      questionPageSize: 10,
      askDialogVisible: false,
      questionForm: {
        title: '',
        content: ''
      },
      questionRules: {
        title: [
          { required: true, message: '请输入问题标题', trigger: 'blur' },
          { min: 5, max: 50, message: '标题长度在5到50个字符之间', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入问题内容', trigger: 'blur' },
          { min: 10, max: 500, message: '内容长度在10到500个字符之间', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchTeacherInfo()
    this.fetchTeacherCourses()
  },
  watch: {
    activeTab(newTab) {
      switch (newTab) {
        case 'materials':
          this.fetchTeacherMaterials()
          break
        case 'reviews':
          this.fetchTeacherReviews()
          break
        case 'questions':
          this.fetchTeacherQuestions()
          break
      }
    }
  },
  methods: {
    async fetchTeacherInfo() {
      this.loading = true
      try {
        const response = await api.teacher.getTeacherDetail(this.teacherId)
        this.teacherInfo = response.data
        this.isFollowing = response.data.isFollowing
      } catch (error) {
        this.$message.error('获取教师信息失败')
      } finally {
        this.loading = false
      }
    },
    async fetchTeacherCourses() {
      try {
        const response = await api.teacher.getTeacherCourses(this.teacherId)
        this.courses = response.data
      } catch (error) {
        this.$message.error('获取课程列表失败')
      }
    },
    async fetchTeacherMaterials() {
      try {
        const response = await api.teacher.getTeacherMaterials(this.teacherId)
        this.materials = response.data
      } catch (error) {
        this.$message.error('获取资料列表失败')
      }
    },
    async fetchTeacherReviews(page = 1) {
      try {
        const response = await api.teacher.getTeacherReviews(this.teacherId, { page })
        this.reviews = response.data.items
        this.totalReviews = response.data.total
        this.ratingDistribution = response.data.distribution
      } catch (error) {
        this.$message.error('获取评价列表失败')
      }
    },
    async fetchTeacherQuestions(page = 1) {
      try {
        const response = await api.teacher.getTeacherQuestions(this.teacherId, { page })
        this.questions = response.data.items
        this.totalQuestions = response.data.total
      } catch (error) {
        this.$message.error('获取问答列表失败')
      }
    },
    async handleFollow() {
      try {
        await api.teacher.toggleFollowTeacher(this.teacherId, !this.isFollowing)
        this.isFollowing = !this.isFollowing
        this.$message.success(this.isFollowing ? '关注成功' : '取消关注成功')
      } catch (error) {
        this.$message.error('操作失败，请稍后重试')
      }
    },
    showAskDialog() {
      this.askDialogVisible = true
      this.questionForm = { title: '', content: '' }
    },
    async submitQuestion() {
      this.$refs.questionForm.validate(async (valid) => {
        if (valid) {
          try {
            await api.teacher.submitQuestion(this.teacherId, this.questionForm)
            this.$message.success('提问成功')
            this.askDialogVisible = false
            if (this.activeTab === 'questions') {
              this.fetchTeacherQuestions()
            }
          } catch (error) {
            this.$message.error('提问失败，请稍后重试')
          }
        }
      })
    },
    handleReviewPageChange(page) {
      this.fetchTeacherReviews(page)
    },
    handleQuestionPageChange(page) {
      this.fetchTeacherQuestions(page)
    },
    getTitleText(title) {
      const titleMap = {
        professor: '教授',
        associate_professor: '副教授',
        lecturer: '讲师',
        assistant: '助教'
      }
      return titleMap[title] || '教师'
    },
    getSubjectText(subject) {
      const subjectMap = {
        math: '数学',
        english: '英语',
        physics: '物理',
        chemistry: '化学',
        biology: '生物'
      }
      return subjectMap[subject] || '综合'
    },
    getMaterialIcon(type) {
      const iconMap = {
        pdf: 'el-icon-document',
        doc: 'el-icon-document-word',
        ppt: 'el-icon-document-ppt',
        video: 'el-icon-video-camera'
      }
      return iconMap[type] || 'el-icon-document'
    }
  },
  filters: {
    materialType(type) {
      const typeMap = {
        pdf: 'PDF文档',
        doc: 'Word文档',
        ppt: 'PPT文档',
        video: '视频文件'
      }
      return typeMap[type] || '其他'
    },
    fileSize(size) {
      if (size < 1024) {
        return size + 'B'
      } else if (size < 1024 * 1024) {
        return (size / 1024).toFixed(1) + 'KB'
      } else {
        return (size / (1024 * 1024)).toFixed(1) + 'MB'
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.teacher-detail {
  padding: 20px;

  .teacher-header {
    background-color: #fff;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .teacher-info {
      display: flex;
      margin-bottom: 20px;

      .avatar-wrapper {
        position: relative;
        margin-right: 20px;

        .avatar {
          width: 120px;
          height: 120px;
          border-radius: 8px;
          object-fit: cover;
        }

        .title-tag {
          position: absolute;
          bottom: 0;
          right: 0;
          background-color: rgba(0, 0, 0, 0.6);
          color: #fff;
          padding: 4px 8px;
          font-size: 12px;
          border-top-left-radius: 4px;
        }
      }

      .info-content {
        flex: 1;

        .name {
          font-size: 24px;
          font-weight: bold;
          margin: 0 0 10px;
        }

        .subject {
          color: #409EFF;
          font-size: 16px;
          margin-bottom: 15px;
        }

        .stats {
          display: flex;
          margin-bottom: 15px;

          .stat-item {
            margin-right: 20px;
            color: #606266;

            i {
              margin-right: 5px;
            }
          }
        }

        .actions {
          .el-button {
            margin-right: 10px;

            &.is-following {
              background-color: #909399;
              border-color: #909399;

              &:hover {
                background-color: #a6a9ad;
                border-color: #a6a9ad;
              }
            }
          }
        }
      }
    }

    .teacher-intro {
      h3 {
        font-size: 18px;
        margin: 0 0 10px;
      }

      p {
        color: #606266;
        line-height: 1.6;
        margin: 0;
      }
    }
  }

  .content-section {
    background-color: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .course-card {
      display: block;
      margin-bottom: 20px;
      border-radius: 8px;
      overflow: hidden;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      transition: transform 0.3s;
      text-decoration: none;
      color: inherit;

      &:hover {
        transform: translateY(-5px);
      }

      .course-cover {
        height: 150px;
        overflow: hidden;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }

      .course-info {
        padding: 15px;

        .title {
          margin: 0 0 10px;
          font-size: 16px;
          font-weight: bold;
        }

        .stats {
          color: #909399;
          font-size: 13px;

          span {
            margin-right: 15px;

            i {
              margin-right: 4px;
            }
          }
        }
      }
    }

    .material-list {
      .material-item {
        margin-bottom: 15px;

        .material-link {
          display: flex;
          align-items: center;
          padding: 15px;
          border-radius: 8px;
          background-color: #f5f7fa;
          text-decoration: none;
          color: inherit;
          transition: background-color 0.3s;

          &:hover {
            background-color: #ecf5ff;
          }

          .material-icon {
            font-size: 24px;
            margin-right: 15px;
            color: #409EFF;
          }

          .material-info {
            flex: 1;

            .title {
              margin: 0 0 5px;
              font-size: 16px;
            }

            .meta {
              color: #909399;
              font-size: 13px;

              span {
                margin-right: 15px;
              }
            }
          }
        }
      }
    }

    .review-section {
      .review-stats {
        margin-bottom: 20px;

        .rating-overview {
          display: flex;
          align-items: flex-start;

          .rating-score {
            text-align: center;
            margin-right: 30px;

            .score {
              font-size: 36px;
              font-weight: bold;
              color: #ff9900;
            }
          }

          .rating-distribution {
            flex: 1;

            .rating-bar {
              display: flex;
              align-items: center;
              margin-bottom: 5px;

              .star-label {
                width: 40px;
                margin-right: 10px;
              }

              .el-progress {
                flex: 1;
                margin-right: 10px;
              }

              .count {
                width: 40px;
                text-align: right;
              }
            }
          }
        }
      }

      .review-list {
        .review-item {
          margin-bottom: 20px;
          padding-bottom: 20px;
          border-bottom: 1px solid #ebeef5;

          &:last-child {
            border-bottom: none;
          }

          .reviewer-info {
            display: flex;
            align-items: center;
            margin-bottom: 10px;

            .avatar {
              width: 32px;
              height: 32px;
              border-radius: 50%;
              margin-right: 10px;
            }

            .username {
              margin-right: 15px;
              font-weight: bold;
            }

            .time {
              color: #909399;
              font-size: 13px;
              margin-left: auto;
            }
          }

          .review-content {
            color: #606266;
            line-height: 1.6;
          }
        }
      }
    }

    .question-list {
      .question-item {
        margin-bottom: 30px;
        padding-bottom: 20px;
        border-bottom: 1px solid #ebeef5;

        &:last-child {
          border-bottom: none;
        }

        .question-header {
          display: flex;
          align-items: center;
          margin-bottom: 10px;

          .avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            margin-right: 10px;
          }

          .username {
            font-weight: bold;
            margin-right: 15px;
          }

          .time {
            color: #909399;
            font-size: 13px;
          }
        }

        .question-content {
          margin-bottom: 15px;

          .title {
            font-size: 16px;
            font-weight: bold;
            margin: 0 0 10px;
          }

          .content {
            color: #606266;
            line-height: 1.6;
            margin: 0;
          }
        }

        .answer {
          background-color: #f5f7fa;
          padding: 15px;
          border-radius: 8px;

          .answer-header {
            display: flex;
            align-items: center;
            margin-bottom: 10px;

            .avatar {
              width: 24px;
              height: 24px;
              border-radius: 50%;
              margin-right: 8px;
            }

            .name {
              font-weight: bold;
              margin-right: 15px;
            }

            .time {
              color: #909399;
              font-size: 13px;
            }
          }

          .answer-content {
            color: #606266;
            line-height: 1.6;
          }
        }
      }
    }
  }

  .pagination {
    margin-top: 20px;
    text-align: center;
  }
}

@media (max-width: 768px) {
  .teacher-detail {
    .teacher-header {
      .teacher-info {
        flex-direction: column;

        .avatar-wrapper {
          margin-right: 0;
          margin-bottom: 20px;
          text-align: center;

          .avatar {
            width: 100px;
            height: 100px;
          }
        }
      }
    }
  }
}
</style> 